import { cloneDeep } from 'lodash-es'
import sortable from 'sortablejs'
import { useExcelExportDownload } from './useExcelExportDownload'

export const OPERATION_PROVIDE = Symbol()

export function useOperation(props, emits) {
  const { data } = toRefs(props)
  const density = ref(props.size || 'medium')
  const densityOptions = [
    {
      label: '默认',
      value: 'medium'
    },
    {
      label: '中等',
      value: 'large'
    },
    {
      label: '紧凑',
      value: 'small'
    }
  ]
  const isDisplayRefres = ref(!!props.request)

  const indexColumn = {
    type: 'index',
    title: '序号',
    key: '_index',
    width: props['indexColumeWidth']
  }

  // const selectColumn = props.columns.find(
  //   (col) => col.type === 'selection'
  // ) || {
  //   type: 'selection'
  // }

  const columns = computed(() => {
    const columnsData = (props.columns as any[]) || []

    const indexColumnIndex = columnsData.findIndex(
      (col) => col.type === 'index'
    )

    if (props['defaultIndexColume'] && indexColumnIndex === -1) {
      const selectColumnIndex = columnsData.findIndex(
        (col) => col.type === 'selection'
      )
      if (selectColumnIndex !== -1) {
        columnsData.splice(selectColumnIndex + 1, 0, indexColumn)
      } else {
        columnsData.unshift(indexColumn)
      }
    }

    columnsData.forEach((item) => {
      if (!item.key) item.key = item.title
      item['align'] = props['columnsAlign']
    })
    return columnsData.filter((item) => item.visiable !== false)
  })

  const columnsSortList = ref<any[]>([])
  const columnValueList = ref<any[]>([])
  const columnSelectList = ref<any[]>([])
  const columnsSetting = reactive({
    displayColumn: true,
    numberColumn: columns.value.some((col) => col.type === 'index'),
    selectColumn: columns.value.some((col) => col.type === 'selection')
  })

  watch(
    columns,
    () => {
      columnsSortList.value = cloneDeep(columns.value)
      columnValueList.value = cloneDeep(columns.value)
      columnSelectList.value = columns.value?.map((v) => v.key)
    },
    {
      immediate: true
    }
  )

  /**
   * 操作
   */

  const columnSelectListChange = (selectValue: string[]) => {
    columnSelectList.value = selectValue
    columnsSetting.displayColumn = selectValue.length === columns.value.length
  }

  const columnsSortChange = (newIndex, oldIndex) => {
    const sortData = columnsSortList.value
    const temp = sortData[newIndex]
    sortData[newIndex] = sortData[oldIndex]
    sortData[oldIndex] = temp
    columnsSortList.value = sortData
  }

  const displayColumnChange = (checked: boolean) => {
    columnsSetting.displayColumn = checked
    if (checked) {
      columnSelectList.value = columnsSortList.value?.map((v) => v.key)
    } else {
      columnSelectList.value = []
    }
  }

  const numberColumnChange = (checked: boolean) => {
    columnsSetting.numberColumn = checked
    if (checked) {
      const numberColumn =
        columns.value.find((col) => col.type === 'index') || indexColumn
      const selectColumnIndex = columnValueList.value.findIndex(
        (col) => col.type === 'selection'
      )
      if (selectColumnIndex !== -1) {
        columnValueList.value.splice(selectColumnIndex + 1, 0, numberColumn)
      } else {
        columnValueList.value.unshift(numberColumn)
      }
    } else {
      const indexColumnIndex = columns.value.findIndex(
        (col) => col.type === 'index'
      )
      columnValueList.value.splice(indexColumnIndex, 1)
    }
  }

  // const selectColumnChange = (checked: boolean) => {
  //   columnsSetting.selectColumn = checked
  //   if (checked) {
  //     columnValueList.value.unshift(selectColumn)
  //     columnsSortList.value.unshift(selectColumn)
  //   } else {
  //     _.remove(columnValueList.value, (col) => col.type === 'selection')
  //     _.remove(columnsSortList.value, (col) => col.type === 'selection')
  //   }
  // }

  const fixedHanle = (index, dir) => {
    if (columnsSortList.value[index].fixed === dir) {
      columnsSortList.value[index].fixed = null
    } else {
      columnsSortList.value[index].fixed = dir
    }
  }

  const resetColumns = () => {
    columnsSortList.value = cloneDeep(columns.value)
    columnSelectList.value = columns.value?.map((v) => v.key)
    columnsSetting.displayColumn = true
    columnsSetting.numberColumn = true
    columnsSetting.selectColumn = columns.value.some(
      (col) => col.type === 'selection'
    )
  }

  const refreshHandle = () => {
    emits('refresh')
  }

  const columnSelectListRef = ref<HTMLDivElement>()
  const sortableOptions = {
    animation: 150,
    onEnd: function (evt) {
      const { newIndex, oldIndex } = evt
      columnsSortChange(newIndex, oldIndex)
    }
  }

  const scrollX = computed(() => {
    if (props['scrollX']) return props['scrollX']
    return columnValueList.value.some((item) => item.fixed) ? 1920 : null
  })

  const columnIndeterminate = computed(() => {
    return (
      !columnsSetting.displayColumn &&
      !!columnSelectList.value.length &&
      columnSelectList.value.length !== columns.value.length
    )
  })

  watchEffect(() => {
    if (columnSelectListRef?.value) {
      sortable.create(columnSelectListRef?.value, sortableOptions)
    }
  })

  watchEffect(() => {
    columnValueList.value = columnsSortList.value?.filter((col) => {
      return (
        columnSelectList.value.includes(col.key) || col.type === 'selection'
      )
    })
  })

  /**
   * 导出功能
   */
  const excelExportDownload = useExcelExportDownload({
    columns: columnValueList,
    data,
    filename: props.filename
  })

  provide(OPERATION_PROVIDE, {
    columnsSetting,
    columnSelectList,
    columnsSortList,
    density,
    densityOptions,
    scrollX,
    columnIndeterminate,
    columnSelectListRef,
    isDisplayRefres,
    refreshHandle,
    displayColumnChange,
    numberColumnChange,
    // selectColumnChange,
    resetColumns,
    columnSelectListChange,
    fixedHanle,
    excelExportDownload
  })

  return {
    columns: columnValueList,
    density,
    scrollX,
    excelExportDownload
  }
}
